package com.hskn.hss.module.tlemployee.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.entity.TreeEntity;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.manufacturer.entity.TlManufacturer;
import com.hskn.hss.module.tldicttype.mapper.TlEmergentDictTypeMapper;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.mapper.TlEmployeeMapper;
import com.hskn.hss.module.tlemployee.service.ITlEmployeeService;
import com.hskn.hss.module.tlemployee.to.TIEmployeeExportTo;
import com.hskn.hss.module.tlemployee.to.TIEmployeeTo;
import com.hskn.hss.module.tlemployee.vo.TlEmployeeExcelOutVO;
import com.hskn.hss.module.tlworktype.entity.TlWorkType;
import com.hskn.hss.module.tlworktype.mapper.TlWorkTypeMapper;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-15
 */
@Api(tags = {"-tl_employee"}, description = "人员档案")
@Slf4j
@RestController
@RequestMapping("/hss/tlemployee")
public class TlEmployeeController {

    @Autowired
    private ISysDepartService departService;
    @Resource
    private TlWorkTypeMapper tlWorkTypeMapper;
    @Autowired
    ITlEmployeeService tlEmployeeService;
    @Resource
    private TlEmployeeMapper tlEmployeeMapper;

    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_employee", bean = TlEmployee.class, beanMapper = TlEmployeeMapper.class, names = "name")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult<Object> insert(@RequestBody @Validated TlEmployee tlEmployee, HttpServletRequest request) {
        try {
            QueryWrapper<TlEmployee> tlEmployeeQueryWrapper = new QueryWrapper<>();
            tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getName, tlEmployee.getName());
            List<TlEmployee> employeeList = tlEmployeeMapper.selectList(tlEmployeeQueryWrapper);
            if (employeeList.isEmpty()) {
                tlEmployeeService.insert(tlEmployee);
                return AjaxResult.success(tlEmployee);
            } else {
                return AjaxResult.fail("该名称已存在，请重新输入");
            }
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_employee", idKey = "id", bean = TlEmployee.class, beanMapper = TlEmployeeMapper.class, names = "name")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult<Object> update(@RequestBody @Validated TlEmployee tlEmployee, HttpServletRequest request) {
        try {
            return tlEmployeeService.update(tlEmployee);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_employee", idKey = "ids", bean = TlEmployee.class, beanMapper = TlEmployeeMapper.class, names = "name")
    @ApiOperation(value = "批量更新接口", notes = "批量更新")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlEmployee.class)
    })
    @RequestMapping(value = "updatebyids", method = RequestMethod.POST)
    public AjaxResult<Object> updatebyids(@RequestBody @Validated TlEmployee tlEmployee, HttpServletRequest request) {
        try {
            return tlEmployeeService.updatebyids(tlEmployee);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_employee", idKey = "id", bean = TlEmployee.class, beanMapper = TlEmployeeMapper.class, names = "name")
    @RequestMapping(value = "deletebyid", method = RequestMethod.POST)
    public AjaxResult<Object> deletebyid(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
            return tlEmployeeService.deletebyid(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_employee", idKey = "ids", bean = TlEmployee.class, beanMapper = TlEmployeeMapper.class, names = "name")
    @ApiOperation(value = "批量删除接口", notes = "批量删除")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlEmployee.class)
    })
    @RequestMapping(value = "deletebatchbyid", method = RequestMethod.POST)
    public AjaxResult<Object> deletebatchbyid(@RequestBody @Validated TlEmployee tlEmployee) {

        try {
            return tlEmployeeService.deletebatchbyid(tlEmployee);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @RequestMapping(value = "getSelectList", method = RequestMethod.POST)
    public AjaxResult<Object> getSelectList(HttpServletRequest request) {
        return AjaxResult.success(tlEmployeeService.getSelectList());
    }


    @RequestMapping(value = "getDetail", method = RequestMethod.POST)
    public AjaxResult<Object> getDetail(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        TlEmployee tlEmployee = null;
        try {
            tlEmployee = tlEmployeeService.getDetail(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
        return AjaxResult.success(tlEmployee);

    }

    @RequestMapping(value = "getList", method = RequestMethod.POST)
    public AjaxResult<Object> getList(@RequestBody @Validated TIEmployeeTo tIEmployeeTo) {
        try {
            BaseEntity entity = new BaseEntity();
            return AjaxResult.success(tlEmployeeService.getList(entity, tIEmployeeTo));
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
    }

    @RequestMapping(value = "tree", method = RequestMethod.POST)
    public AjaxResult<Object> tree(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            List<TreeEntity> emplTree = tlEmployeeService.getEmplTree(params);
            return AjaxResult.success(emplTree);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("查询失败，请稍后再试");
        }
    }

    @RequestMapping(value = "empltree", method = RequestMethod.POST)
    public AjaxResult<Object> empltree(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            List<TreeEntity> emplTree = tlEmployeeService.getEmplTree2(params);
            return AjaxResult.success(emplTree);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("查询失败，请稍后再试");
        }
    }

    @RequestMapping(value = "getuserList", method = RequestMethod.POST)
    public AjaxResult<Object> getuserList(HttpServletRequest request) {
        return AjaxResult.success(tlEmployeeService.getuserList());
    }

    /**
     * 获取列表
     *
     * @param request
     * @return
     */
//    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_employee", bean = TlEmployee.class, beanMapper = TlEmployeeMapper.class, names = "name")
    @ApiOperation(value = "人员档案导入接口", notes = "人员档案导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request, @Validated ExcelReaderTO excelReaderTo) {
        try {

            MultipartFile file = excelReaderTo.getFiles();
            if (Arrays.stream(ExcelTypeEnum.values()).noneMatch(s -> s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))) {
                return AjaxResult.fail("导入文件格式错误");
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlEmployee> util = new ExcelUtil<TlEmployee>(TlEmployee.class);
            List<TlEmployee> tlEmployeeList = util.importExcel(inputStream);
            if (tlEmployeeList.isEmpty()) {
                return AjaxResult.fail("导入内容为空");
            }
            tlEmployeeService.excelReader(tlEmployeeList);
//
//            //车牌号为空判断
//            String message = "";
//            boolean ck = false;
//            for(TlEmployee tl : tlEmployeeList){
//                if(StringUtils.isEmpty(tl.getEmplnum())){
//                    message +="工号不能为空;##";
//                } else if(StringUtils.isEmpty(tl.getName())){
//                    message +="姓名不能为空;##";
//                }
//            }
//            //导入重复判断
//            List<TlEmployee> tlEmployees = tlEmployeeMapper.selectList(new QueryWrapper<>());
//            Map<String,List<TlEmployee>> map = tlEmployees.stream().collect(Collectors.groupingBy(TlEmployee::getEmplnum));
//            //导入文件内部重复判断
//            List<String> code = tlEmployees.stream().map(TlEmployee::getEmplnum).collect(Collectors.toList());
//            if(AttributeUtils.RepeatedCheck(code) == false){
//                message +="导入文件中工号有重复;##";
//            }
//            for(TlEmployee tl : tlEmployeeList) {
//                if (CollectionUtils.isNotEmpty(map.get(tl.getEmplnum()))) {
//                    message += "档案中已存在工号:" + tl.getEmplnum() + ";##";
//                }
//            }
//            if(StringUtils.isNotEmpty(message)){
//                return AjaxResult.fail("您导入的数据:##"+message);
//            }
            if (tlEmployeeService.saveBatch(tlEmployeeList)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception exception) {
            exception.printStackTrace();
            return AjaxResult.fail();
        }
    }

    @ApiOperation(value = "人员档案导出接口", notes = "人员档案导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request, @RequestBody TIEmployeeExportTo tiEmployeeExportTo) {
        try {
            if(tiEmployeeExportTo.getIds()!=null&&tiEmployeeExportTo.getIds().isEmpty()){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            QueryWrapper<TlEmployee> tlEmployeeQueryWrapper = new QueryWrapper<>();
            QueryWrapper<TlWorkType> tlWorkTypeQueryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(tiEmployeeExportTo.getDeptid())) {
                tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getDeptid, tiEmployeeExportTo.getDeptid());
            }
            if (StringUtils.isNotEmpty(tiEmployeeExportTo.getName())) {
                tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getName, tiEmployeeExportTo.getName());
            }
            if (StringUtils.isNotEmpty(tiEmployeeExportTo.getEmplnum())) {
                tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getEmplnum, tiEmployeeExportTo.getEmplnum());
            }
            if (StringUtils.isNotEmpty(tiEmployeeExportTo.getPhonenum())) {
                tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getPhonenum, tiEmployeeExportTo.getPhonenum());
            }
            if (StringUtils.isNotEmpty(tiEmployeeExportTo.getStatus())) {
                tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getStatus, tiEmployeeExportTo.getStatus());
            }
            if (StringUtils.isNotEmpty(tiEmployeeExportTo.getWorktype())) {
                tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getWorktype, tiEmployeeExportTo.getWorktype());
            }
            if (tiEmployeeExportTo.getIds() != null && !tiEmployeeExportTo.getIds().isEmpty()) {
                tlEmployeeQueryWrapper.lambda().in(TlEmployee::getId, tiEmployeeExportTo.getIds());
            }
            List<TlEmployee> tlEmployeeList = tlEmployeeMapper.selectList(tlEmployeeQueryWrapper);
            if (tlEmployeeList.isEmpty()) {
                return com.hskn.hss.core.domain.AjaxResult.error("导出数据为空");
            }
            ExcelUtil<TlEmployeeExcelOutVO> util = new ExcelUtil<TlEmployeeExcelOutVO>(TlEmployeeExcelOutVO.class);
            List<TlEmployeeExcelOutVO> tlEmployeeExcelOutVOList = JSONObject.parseArray(JSONObject.toJSONString(tlEmployeeList), TlEmployeeExcelOutVO.class);
            Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
            List<TlWorkType> tlWorkTypeList = tlWorkTypeMapper.selectList(tlWorkTypeQueryWrapper);
            Map<String, TlWorkType> tlWorkTypeMap = GroupingByUtils.getGroupingForMapEntity(tlWorkTypeList, TlWorkType::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));

            for (TlEmployeeExcelOutVO tlEmployeeExcelOutVO : tlEmployeeExcelOutVOList) {
                if (departMap.containsKey(tlEmployeeExcelOutVO.getEmpldeptid())) {
                    tlEmployeeExcelOutVO.setDeptName(departMap.get(tlEmployeeExcelOutVO.getEmpldeptid()).getDepartName());
                }
                if (tlWorkTypeMap.containsKey(tlEmployeeExcelOutVO.getWorktype())) {
                    tlEmployeeExcelOutVO.setWorktypeName(tlWorkTypeMap.get(tlEmployeeExcelOutVO.getWorktype()).getWorktype());
                }
            }
            return util.exportExcel(tlEmployeeExcelOutVOList, "人员档案");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }

    @ApiOperation(value = "人员档案导出模板接口", notes = "人员档案模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlEmployeeExcelOutVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<TlEmployee> util = new ExcelUtil<TlEmployee>(TlEmployee.class);
            //数据载体转换
            List<TlEmployee> tlEmployeeExcelOutVOList = new ArrayList<>();
            //导出
            return util.exportExcel(tlEmployeeExcelOutVOList, "人员档案模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }

    @RequestMapping(value = "getGridList", method = RequestMethod.POST)
    public AjaxResult<Object> getGridList(@RequestBody @Validated TIEmployeeTo tiEmployeeTo) {
        try {
            return AjaxResult.success(tlEmployeeService.getGridList(tiEmployeeTo));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("查询失败，请稍后再试");
        }
    }

}

